//
//  PlayVideoViewController.m
//  MMLOOK
//
//  Created by dllo on 15/10/10.
//  Copyright © 2015年 武俊娥. All rights reserved.
//

#import "PlayVideoViewController.h"
#import "Player.h"
#import "BarView.h"
#import "BackView.h"
#import <AVFoundation/AVFoundation.h>
#import "MBProgressHUD.h"

@interface PlayVideoViewController ()<BarViewDelegate,BackViewDelegate>

@property (nonatomic, assign) CMTime totalTime;//记录视频总时长
@property(nonatomic, retain)NSString *totalTimeText; //视频总时长 转化成时间

@property(nonatomic, retain)NSDateFormatter *dateFormatter;


@property (nonatomic, assign) BOOL hidenBar;//视频UI控件是否显示的标识

@property(nonatomic, assign)BOOL played;  //是否在播放

@property (nonatomic, assign) BOOL didPlay;//缓冲结束立即播放的标识



@property (nonatomic ,strong) AVPlayer *player;
@property (nonatomic ,strong) AVPlayerItem *playerItem; //AVPlayerItem是avplayer对象的呈现状态

@property (retain, nonatomic) Player *playView;
@property  (nonatomic, retain)BarView *barView;
@property (nonatomic, retain)BackView *backView;

@property (nonatomic ,assign) id playbackTimeObserver;


@property (nonatomic, retain)MBProgressHUD *mbProView;



@end

@implementation PlayVideoViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       
        
        
    }
    
    return self;
}

-(void)dealloc
{
    

    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBarHidden = YES;
    
    NSURL *videoUrl = [NSURL URLWithString:self.playUrl];
    
    self.playerItem = [AVPlayerItem playerItemWithURL:videoUrl];
    
    //创建视图
    [self creatView];
    [self creatMB];
    
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];

    self.playView.player = self.player;
    
    // 监听播放状态
    [self monitoringPlayback:self.playerItem];
    
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    // 添加视频播放结束通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    
}

//加载动画
-(void)creatMB
{
    // 添加加载动画
    self.mbProView = [[MBProgressHUD alloc] initWithView:self.playView];
    self.mbProView.mode = MBProgressHUDModeIndeterminate;// 样式 菊花
    self.mbProView.labelText = @"(｢･ω･)｢ 加载中";
    [self.mbProView show:YES];
    [self.playView addSubview:self.mbProView];
}


//创建视图
-(void)creatView
{
    self.playView = [[Player alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width)];
    self.playView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.playView];
    
    //点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.playView addGestureRecognizer:tap];
    
    
    //自定义的菜单
    self.barView = [[BarView alloc]initWithFrame:CGRectMake(0, self.playView.frame.size.height - 50, self.playView.frame.size.width, 50)];
    self.barView.delegate = self;
    [self.playView addSubview:self.barView];
    
    //返回菜单
    self.backView = [[BackView alloc]initWithFrame:CGRectMake(0, 0, self.playView.frame.size.width, 40)];
    self.backView.title = self.title;
    self.backView.delegate = self;
    [self.playView addSubview:self.backView];
    

    [UIView animateWithDuration:0.2 animations:^{
        //旋转
    self.playView.transform = CGAffineTransformMakeRotation(90 *M_PI / 180.0);
    self.playView.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2.0, ([UIScreen mainScreen].bounds.size.height)/2.0);
        
        
        self.barView.playButton.frame = CGRectMake(40, 10, 30, 30);
        self.barView.playProgress.frame = CGRectMake(80, 25, self.barView.frame.size.width - 180, 10);
        self.barView.playSlider.frame = CGRectMake(77, 21.2, self.barView.frame.size.width - 180 + 10, 10);
        self.barView.totalTimeLabel.frame = CGRectMake(self.barView.frame.size.width - 100, 22, 100, 10);
        
    }];
    
}

-(void)backLastView
{
    
    [self.playView.player.currentItem cancelPendingSeeks];
    [self.playView.player.currentItem.asset cancelLoading];
    
    [self.playView.player pause];
    [self.playView removeFromSuperview];
    
    //返回上一页
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark - 监控
//用于监听每秒的状态
- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    
    UISlider *slider = self.barView.playSlider;//获取当前滑动条
 
    //这里设置每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 10.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        float current = CMTimeGetSeconds(time);//获取当前的播放时间
        
        if (current) {
            [slider setValue:current animated:YES];//实时设置滑动条当前值
            int currentTime = (int)current;
            int m = currentTime / 60;
            int s = currentTime % 60;
            NSString *strM = nil;
            NSString *strS = nil;
            if (m < 10) {
                strM = [NSString stringWithFormat:@"0%d", m];
            } else {
                strM = [NSString stringWithFormat:@"%d", m];
            }
            if (s < 10) {
                strS = [NSString stringWithFormat:@"0%d", s];
            } else {
                strS = [NSString stringWithFormat:@"%d", s];
            }
    
        self.barView.totalTimeLabel.text = [NSString stringWithFormat:@"%@/%@",[NSString stringWithFormat:@"%@:%@", strM, strS],self.totalTimeText];// 转换成播放时间
            
        }
    }];
    
}



//移除所有通知
- (void)removeNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


//通知移除方法
- (void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem
{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}


//实现KVO的方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"status"]) {
        
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            
            NSLog(@"AVPlayerStatusReadyToPlay");
            
            //加载动画去除
            [self.mbProView release];
            
            // 获取视频总长度
            self.totalTime = self.playerItem.duration;
            
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
            
            self.totalTimeText = [self convertTime:totalSecond];
            
           self.barView.totalTimeLabel.text = [NSString stringWithFormat:@"%@/%@",@"00",self.totalTimeText];// 转换成播放时间
            
            // 自定义UISlider外观
            [self customVideoSlider: self.totalTime];
            
            NSLog(@"movie total duration:%f",CMTimeGetSeconds( self.totalTime));
            
        } else if ([playerItem status] == AVPlayerStatusFailed) {

            
            //加载动画去除
            [self.mbProView release];
            NSLog(@"AVPlayerStatusFailed");
        }
        
        
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {

        NSArray *array = playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
        
        //设置缓存条
        [self.barView.playProgress setProgress:totalBuffer/CMTimeGetSeconds(self.totalTime) animated:YES];
        
        float currentPlayTime =  CMTimeGetSeconds([self.player currentTime]);//获取当前播放时长
        
        //设定当缓冲总时长超过播放时长3秒时开始播放视频
        if (totalBuffer - currentPlayTime > 3.0) {
            if (!self.didPlay) {
                [self.player play];
                [self.mbProView hide:YES];
                [self.barView.playButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
                self.didPlay = YES;
            }
            
        } else {
            
            [self.player pause];
            [self.mbProView show:YES];
            self.didPlay = NO;
            [self.barView.playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        }
        
    }
}



// 计算缓冲进度
- (NSTimeInterval)availableDuration {
    
    NSArray *loadedTimeRanges = [[self.playView.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}




// 当视频播放结束时
- (void)moviePlayDidEnd:(NSNotification *)notification {
    
    //返回上一页吧
    [self.navigationController popViewControllerAnimated:YES];
    
}



//菜单的显示 / 消失
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    if (self.hidenBar) {
        
        self.hidenBar = NO;
        
    } else {
        
        self.hidenBar = YES;
        
    }
    
    self.barView.hidden = self.hidenBar;
    self.backView.hidden = self.hidenBar;
}



//滑动进度条
- (void)sliderActionWith:(UISlider *)slider
{

    if (self.player.rate == 0) {
        [self.player seekToTime:CMTimeMake((int)slider.value*10, 10.0)];
        [self.player play];
        [self.barView.playButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    } else if (self.player.rate == 1) {
        [self.player pause];
        [self.player seekToTime:CMTimeMake((int)slider.value*10, 10.0)];
        [self.player play];
        [self.barView.playButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    }

}



// 播放 / 暂停
- (void)playButtonActionWith:(UIButton *)button
{

    if (self.player.rate == 0) {
        
       [self.barView.playButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        
        if (self.didPlay) {
          [self.playView.player play];
        }
        
    } else {
        
        [self.playView.player pause];
        
        [self.barView.playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    }


}


//UISlider基本设置
- (void)customVideoSlider:(CMTime)duration
{
    //最大值
    self.barView.playSlider.maximumValue = CMTimeGetSeconds(duration);
    
    self.barView.playSlider.minimumValue = 0.0;
}




// 将时间转换为播放时间
- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    if (second/3600 >= 1) {
        //判断是否超过1小时
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
    } else {
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [[self dateFormatter] stringFromDate:d];
    return showtimeNew;
}


//时间转化判断
- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
